//
// Created by denglibin on 2020/5/17.
//

#include <stdio.h>
#include <iconv.h>
#include <string.h>
#include <stdlib.h>
#include "../header/utf2gbk.h"

int UTF8toGBK(char *inbuf, char *outbuf, size_t outlen)
{
    iconv_t cd;
    char **pin = &inbuf;
    char **pout = &outbuf;
    size_t inlen = strlen(inbuf);
    cd = iconv_open("gbk", "utf-8"); // gb2312
    if (0 == cd)
        return -1; 
    if (-1 == iconv(cd, pin, &inlen, pout, &outlen))
    {
        iconv_close(cd);
        return -1;
    }

    iconv_close(cd);
    return 0;
}

void print_utf8_2_gbk(char *inbuf)
{
    size_t inlen = strlen(inbuf);
    char *buf = calloc(inlen, 1);
    UTF8toGBK(inbuf, buf, inlen);
    printf("%s", buf);
    free(buf);
}

int main26()
{
    char *str_in = "hello中国";
    size_t in_len = strlen(str_in);

    char *str_out_buf = (char*)calloc(in_len, 1);

    UTF8toGBK(str_in, str_out_buf, 32);
    printf("%s\n", str_out_buf);

    print_utf8_2_gbk("utf8字节序列:");
    for(int i = 0; i < in_len; i++){
        printf("%#x ", str_in[i]);
    }

    print_utf8_2_gbk("\ngbk字节序列:");
    for(int i = 0; i < in_len; i++){
        printf("%#x ", str_out_buf[i]);
    }
    free(str_out_buf);

    print_utf8_2_gbk("\nEnglish中文");
    return 0;
}
